package com.x.erp.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

import com.x.framework.Base;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.x.erp.model.CarConfInfo;
import com.x.framework.dao.BaseDao;
@Repository
public class CarConfInfoDao extends BaseDao {

	private final static String selectConfSql = "SELECT " + 
			"bcc.*, " + 
			"ecci.CAR_ID IS NOT NULL AS SELECTED_STATE " + 
			"FROM " + 
			"BASE_CAR_CONF bcc " + 
			"LEFT JOIN ERP_CAR_CONF_INFO ecci ON bcc.CONF_ID = ecci.CONF_ID AND ecci.CAR_ID = ? ";
	/**
	 * 查询车辆配置信息
	 * @param carConfInfo
	 * @return
	 * @throws Exception 
	 */
	public List<Map<String, Object>> selectCarConfInfo(CarConfInfo carConfInfo) throws Exception {
		StringBuilder sql = new StringBuilder(selectConfSql);
		List<Object> params = new ArrayList<Object>();
		params.add(carConfInfo.getCarId());
		sql.append("ORDER BY bcc.CONF_SEQ ");
		RowMapper<Map<String, Object>> mapper = new RowMapper<Map<String, Object>>() {
			public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("confId", rs.getInt("CONF_ID"));
				map.put("confName", rs.getString("CONF_NAME"));
				map.put("confSeq", rs.getInt("CONF_SEQ"));
				map.put("confKey", rs.getString("CONF_KEY"));
				map.put("confParentId", rs.getInt("CONF_PARENT_ID"));
				map.put("confBrightSpot", rs.getInt("CONF_BRIGHT_SPOT"));
				map.put("selectedState", rs.getBoolean("SELECTED_STATE"));
				return map;
			}
		};
		return this.queryForList(sql.toString(), mapper, params);
	}

	private final static String insertCarConfInfoListSql = "INSERT INTO ERP_CAR_CONF_INFO VALUES ";
	/**
	 * 批量插入车辆配置信息
	 * @param carConfInfo
	 * @return
	 * @throws Exception
	 */
	public void insertCarConfInfoList(CarConfInfo carConfInfo, String[] carConfIds) throws Exception {
		StringBuilder sql = new StringBuilder(insertCarConfInfoListSql);
		List<Object> params = new ArrayList<>();
		if (carConfIds == null || carConfIds.length == 0){
			return;
		} else {
			for (int i = 0;i < carConfIds.length;i++){
				if (i == 0 ){
					sql.append("(?,?) ");
					params.add(carConfInfo.getCarId());
					params.add(carConfIds[i]);
				} else {
					sql.append(",(?,?) ");
					params.add(carConfInfo.getCarId());
					params.add(carConfIds[i]);
				}
			}
			this.execute(sql.toString(), params);
		}
	}

}
